import store from "store";
import { delEmptyChildren } from "@/utils";
const fMenu = {
	meta: {
		label: "首页"
	},
	path: "/",
	active: true
};
export default {
	namespaced: true,
	state: {
		bankTypes: store.get("bankTypes") || [],
		brands: store.get("brands") || [],
		// 分公司数据
		bizCompany: store.get("bizCompany") || [],
		bizBrands: store.get("bizBrands") || [],
		dept: store.get("dept") || [],
		staff: store.get("staff") || [],
		visibleCusDetail: false,
		cusFormSubmit: false,
		refundState: false, //刷新财务打款
		visibleAppointForm: false,
		keepAliveList: [], //页面缓存
		visitedViews: [fMenu] //tag标签
	},
	getters: {
		company: state => state.company
	},
	actions: {
		// 初始化
		async initData({ dispatch }) {
			// dispatch("getCompany");
			return Promise.all([
				// dispatch("getCompany"),
				// dispatch("getBusiness")
				// dispatch("getBrands")
				dispatch('getBankType')
			]);
		},
		async getBankType({ commit }) {
			return this.$service.orderrefund.bankType().then((data) => {
				let list = (data ?? []).map(v => ({
					label: v.name,
					value: v.id
				}))
				commit('SET_BANK_TYPE', list)
			})
		},
		/**
		 * 获取事业部
		 */
		async getGroupList({ commit }, params = {}) {
			return this.$service.public.getGroupList(params).then(data => {
				return data || [];
			});
		},
		/**
		 * 获取品牌
		 */
		async getBrands({ commit }) {
			return this.$service.brand.page({}).then(data => {
				let list = (data || []).map(v => ({ ...v, label: v.bra_name, value: v.bra_id }));
				commit("SET_BRANDS", list);
				return list;
			});
		},
		/**
		 * 根据事业部获取分公司
		 * @obj biz_id 事业部id, needAll 是否在数组到插入-全部
		 */
		async getBizCompany({ commit }, obj) {
			const { biz_id = "", needAll = true } = obj;
			delete obj.needAll;
			return this.$service.company.list({ biz_id }).then((data = []) => {
				data.length != 1 &&
					needAll &&
					data.unshift({
						label: "全部",
						company_name: "全部",
						value: "",
						company_id: ""
					});

				commit("SET_BIZ_COMPANY", data);
				return data || [];
			});
		},
		/**
		 * 根据事业部获取品牌
		 * @param params biz_id 事业部id, needAll 是否在数组到插入-全部
		 */
		async getBizBrands({ commit }, params) {
			const { needAll = true, ...args } = params;
			return this.$service.brand.usermanage(args).then(data => {
				let list = (data || []).map(v => ({ ...v, label: v.bra_name, value: v.bra_id }));
				list.length != 1 &&
					needAll &&
					list.unshift({
						label: "全部",
						bra_name: "全部",
						value: "",
						bra_id: ""
					});

				commit("SET_BIZ_BRANDS", list);
				return list;
			});
		},
		/**
		 * 获取部门
		 * @param params biz_id 事业部id, needAll 是否在数组到插入-全部
		 */
		 async getDept({ commit }, params) {
			const { needAll = true, needCascader = false, ...args } = params;
			return this.$service.dept.list({ parent_id: 0, is_store: 0, ...args }).then(data => {
				let list = data || [];
				if (!needCascader) {
					list = (data || []).reduce((prev, curr) => [...prev, ...delEmptyChildren(curr.children)], []);
					list.length != 1 &&
						needAll &&
						list.unshift({
							label: "全部",
							dept_name: "全部",
							value: "",
							dept_id: ""
						});
				}
				commit("SET_DEPT", list);
				return list;
			});
		},

		//员工列表
		async getStaff({ commit }, params) {
			const { needAll = true, ...arg } = params;
			return this.$service.user.list(arg).then(res => {
				let list = res.data ?? [];
				list.length != 1 &&
					needAll &&
					list.unshift({
						label: "全部",
						user_name: "全部",
						value: "",
						user_id: ""
					});
				commit("SET_STAFF", list);
				return list;
			});
		},
		//员工列表
		async getDeptStaff({ commit }, params) {
			const { needAll = true, ...arg } = params;
			return this.$service.user.deptuserlists(arg).then(data => {
				let list = data ?? [];
				list.length != 1 &&
					needAll &&
					list.unshift({
						label: "全部",
						user_name: "全部",
						value: "",
						user_id: ""
					});
				commit("SET_STAFF", list);
				return list;
			});
		},
		//添加页面缓存name
		addView({ dispatch }, view) {
			dispatch("addVisitedView", view);
			dispatch("addCachedView", view);
		},
		addCachedView({ commit }, view) {
			commit("ADD_CACHED_VIEW", view);
		},
		addVisitedView({ commit }, view) {
			commit("ADD_VISITED_VIEW", view);
		},
		//删除当前
		delView({ dispatch, state }, view) {
			return new Promise(resolve => {
				dispatch("delVisitedView", view);
				dispatch("delCachedView", view);
				resolve({
					visitedViews: [...state.visitedViews],
					keepAliveList: [...state.keepAliveList]
				});
			});
		},
		delVisitedView({ commit, state }, view) {
			return new Promise(resolve => {
				commit("DEL_VISITED_VIEW", view);
				resolve([...state.visitedViews]);
			});
		},
		delCachedView({ commit, state }, view) {
			return new Promise(resolve => {
				commit("DEL_CACHED_VIEW", view);
				resolve([...state.keepAliveList]);
			});
		},
		//关闭其他
		delOthersViews({ dispatch, state }, view) {
			return new Promise(resolve => {
				dispatch("delOthersVisitedViews", view);
				dispatch("delOthersCachedViews", view);
				resolve({
					visitedViews: [...state.visitedViews],
					cachedViews: [...state.keepAliveList]
				});
			});
		},
		delOthersVisitedViews({ commit, state }, view) {
			return new Promise(resolve => {
				commit("DEL_OTHERS_VISITED_VIEWS", view);
				resolve([...state.visitedViews]);
			});
		},
		delOthersCachedViews({ commit, state }, view) {
			return new Promise(resolve => {
				commit("DEL_OTHERS_CACHED_VIEWS", view);
				resolve([...state.keepAliveList]);
			});
		},
		//关闭所有
		delAllViews({ dispatch, state }, view) {
			return new Promise(resolve => {
				dispatch("delAllVisitedViews", view);
				dispatch("delAllCachedViews", view);
				resolve({
					visitedViews: [...state.visitedViews],
					cachedViews: [...state.keepAliveList]
				});
			});
		},
		delAllVisitedViews({ commit, state }) {
			return new Promise(resolve => {
				commit("DEL_ALL_VISITED_VIEWS");
				resolve([...state.visitedViews]);
			});
		},
		delAllCachedViews({ commit, state }) {
			return new Promise(resolve => {
				commit("DEL_ALL_CACHED_VIEWS");
				resolve([...state.keepAliveList]);
			});
		}
	},
	mutations: {
		SET_BANK_TYPE(state, list) {
			state.bankTypes = list
			store.set("bankTypes", list);
		},
		SET_BRANDS(state, list) {
            state.brands = list;
            store.set("brands", list);
        },
		// 客户详情打开状态
		SET_VISIBLE_CUS_DETAIL(state, visible = false) {
			state.visibleCusDetail = visible;
		},
		// 创建客户表单状态
		SET_CUS_FORM_SUBMIT(state, submiting = false) {
			state.cusFormSubmit = submiting;
		},
		//退款刷新
		SET_REFUND_STATE(state, status = false) {
			state.refundState = status;
		},
		// 预约表单打开状态
		SET_VISIBLE_APPOINT_FORM(state, visible = false) {
			state.visibleAppointForm = visible;
		},
		SET_BIZ_COMPANY(state, list) {
			state.bizCompany = list;
			store.set("bizCompany", list);
		},
		SET_BIZ_BRANDS(state, list) {
			state.bizBrands = list;
			store.set("bizBrands", list);
		},
		SET_DEPT(state, list) {
			state.dept = list;
			store.set("dept", list);
		},
		SET_STAFF(state, list) {
			state.staff = list;
			store.set("staff", list);
		},
		//添加页面缓存name
		ADD_CACHED_VIEW(state, view) {
			if (state.keepAliveList.includes(view.name)) return;
			state.keepAliveList.push(view.name);
		},
		ADD_VISITED_VIEW(state, item) {
			const index = state.visitedViews.findIndex(e => e.path === item.path);

			state.visitedViews.forEach(e => {
				e.active = e.path == item.path;
			});
			if (index < 0) {
				if (item.path == "/") {
					item.meta = fMenu.meta;
				}

				if (item?.meta?.label) {
					state.visitedViews.push({
						...item,
						active: true
					});
				}
				return;
			}
			state.visitedViews[index].active = true;
			state.visitedViews[index].meta = item.path == "/" ? fMenu.meta : item.meta;
			state.visitedViews[index].path = item.path;
			state.visitedViews[index].name = item.name;
		},
		//删除当前
		DEL_CACHED_VIEW(state, view) {
			const index = state.keepAliveList.indexOf(view.name);
			index > -1 && state.keepAliveList.splice(index, 1);
		},
		DEL_VISITED_VIEW(state, view) {
			for (const [i, v] of state.visitedViews.entries()) {
				if (v.path === view.path) {
					state.visitedViews.splice(i, 1);
					break;
				}
			}
		},
		//关闭其他
		DEL_OTHERS_VISITED_VIEWS(state, view) {
			state.visitedViews = state.visitedViews.filter(v => {
				return v.meta.affix || v.path === "/" || v.path === view.path;
			});
		},
		DEL_OTHERS_CACHED_VIEWS(state, view) {
			const index = state.keepAliveList.indexOf(view.name);
			if (index > -1) {
				state.keepAliveList = state.keepAliveList.slice(index, index + 1);
			} else {
				state.keepAliveList = [];
			}
		},
		//关闭所有
		DEL_ALL_VISITED_VIEWS(state) {
			state.visitedViews = [fMenu];
		},
		DEL_ALL_CACHED_VIEWS(state) {
			state.keepAliveList = [];
		}
	}
};
